<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With, raw");

namespace Sweety\Controllers;

require 'vendor/autoload.php';

use Firebase\JWT\JWT;

class UserController
{

    private static $db;
    private static $secretKey = "83b5931995b15bae8f79f5348e360ebadc0b54531d803604ead67878285ef229"; // Секретный ключ для подписи токена
    private static $dbHost = 'mysql';
    private static $dbName = 'dev';
    private static $dbUser = 'dev';
    private static $dbPassword = 'dev';
    private static $dbPort = 3306;

    public static function setDatabase($db)
    {
        self::$db = $db;
    }

    public static function register()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $userName = $data['username'] ?? '';
        $password = $data['password'] ?? '';
        $email = $data['email'] ?? '';

        return self::registerUser($userName, $password, $email);
    }

    public static function registerUser($username, $password, $email)
    {
        self::initialize();

        if (empty($username) || empty($password) || empty($email)) {
            return ['error' => 'Переданы не все значения'];
        }

        // Проверяем, существует ли пользователь с таким же именем или email
        if (self::getUserByUsername($username)) {
            return ['error' => 'Пользователь с таким именем уже существует'];
        }

        if (self::getUserByEmail($email)) {
            return ['error' => 'Пользователь с таким email уже существует'];
        }

        // Хешируем пароль
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);

        // Добавляем пользователя в базу данных
        $stmt = self::$db->prepare("INSERT INTO users (username, password_hash, email) VALUES (?, ?, ?)");
        $stmt->bind_param('sss', $username, $passwordHash, $email);

        if ($stmt->execute()) {
            $user = self::getUserByUsername($username);
            return ['user_id' => $user['id']];
        } else {
            return ['error' => 'Ошибка регистрации'];
        }
    }

    public static function login()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $userName = $data['username'] ?? '';
        $password = $data['password'] ?? '';
        echo json_encode(self::loginUser($userName, $password));
    }

    public static function loginUser($username, $password)
    {
        self::initialize();

        $user = self::getUserByUsername($username);

        if (empty($user)) {
            $user = self::getUserByEmail($username);
        }

        if (!$user || !password_verify($password, $user['password_hash'])) {
            return ['error' => 'Неверное имя пользователя или пароль'];
        }

        $token = self::generateToken($user['id'], $user['username']);

        return ['accessToken' => $token];
    }

    private static function getUserByUsername($username)
    {
        $stmt = self::$db->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $result = $stmt->get_result();

        return $result->fetch_assoc();
    }

    private static function getUserByEmail($email)
    {
        $stmt = self::$db->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $result = $stmt->get_result();

        return $result->fetch_assoc();
    }

    private static function generateToken($userId, $username)
    {
        $issuedAt = time();
        $expirationTime = $issuedAt + 60 * 60;  // Токен истечет через 1 час
        $payload = [
            'user_id' => $userId,
            'username' => $username,
            'iat' => $issuedAt,
            'exp' => $expirationTime
        ];

        return JWT::encode($payload, self::$secretKey, 'HS256');
    }

    public static function validateToken($token)
    {
        self::initialize();

        try {
            $headers = ['HS256'];
            $decoded = JWT::decode($token, self::$secretKey, $headers);
            return (array)$decoded;
        } catch (\Exception $e) {
            return ['error' => 'Неверный токен'];
        }
    }

    private static function initialize()
    {
        self::$db = new \mysqli(self::$dbHost, self::$dbUser, self::$dbPassword, self::$dbName, self::$dbPort);
        if (self::$db->connect_error) {
            die("Ошибка подключения: " . self::$db->connect_error);
        }
    }
}

?>
